package com.gitee.wsl.time.statistics

import com.gitee.wsl.time.T
import kotlin.time.Duration
import kotlin.time.TimedValue


interface TaskStatisticsCollector {

    fun addElapsedTime(task: String, elapsed: Duration)

    fun getMeasuredDurationsFor(task: String): List<Duration>?

    fun getStatisticsFor(task: String): TaskStatistics?

    fun logStatistics(task: String)

    fun logAllStatistics()

}

interface TaskStatisticScope{
    fun measureTime(name:String = "task",block: () -> Unit):Duration
    fun <T> measureTimedValue(name: String = "task" ,block: () -> T): TimedValue<T>
}

fun T.taskStatistic(block:TaskStatisticScope.()->Unit):TaskStatisticsCollector{
   val reg = object:DefaultTaskStatisticsCollector(),TaskStatisticScope{

       override fun measureTime(name: String, block: () -> Unit):Duration {
          val runtime = kotlin.time.measureTime(block)
          addElapsedTime(name,runtime)
           return runtime
       }

       override fun <T> measureTimedValue(name: String, block: () -> T): TimedValue<T> {
           val runtime = kotlin.time.measureTimedValue(block)
           addElapsedTime(name,runtime.duration)
           return runtime
       }
   }
   reg.block()
   reg.logAllStatistics()
   return reg
}